<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Support\Collection;

class GroupbuyBase extends Model
{
    const WILLSTART = 0; // 未开始
    const NORMAL    = 2; // 正常
    const FINISHED  = 3; // 结束

    protected $table = 'yf_groupbuy_base';
    protected $primaryKey = 'groupbuy_id';
    public $timestamps = false;
    protected $guarded = ['groupbuy_id'];

    public function goodsCommon()
    {
        return $this->hasOne(GoodsCommon::class, 'common_id', 'common_id');
    }

    /**
     * 获取首页版块中团购信息
     * 不返回过期失效的团购商品，不返回已经下架的团购商品
     * @param $ids
     * @return array
     */
    public static function getForumGroupbuy(array $ids = []) : array
    {
        $data = [];
        if (empty($ids)) return $data;

        $groupbuy_list = self::getNormalGroupbuy($ids);
        if ($groupbuy_list->isEmpty()) return $data;

        $goods_ids = $groupbuy_list->pluck('goods_id')->toArray();
        $goods_rows = GoodsBase::getGoodsListByGoodsId($goods_ids);
        $groupbuy_list->each(function ($groupbuy, $index) use (&$data, $goods_rows) {
            if (now()->isBefore($groupbuy->groupbuy_endtime) && $groupbuy->groupbuy_state == self::NORMAL) {
                $data[$index] = $groupbuy->only([
                    'groupbuy_id', 'goods_id', 'groupbuy_image_rec', 'groupbuy_image',
                    'groupbuy_name', 'shop_name', 'groupbuy_endtime', 'groupbuy_starttime',
                    'groupbuy_buyer_count', 'groupbuy_price', 'groupbuy_buy_quantity'
                ]);
                $goods_row = $goods_rows->where('goods_id', $groupbuy->goods_id)->first();
                $data[$index]['goods_name'] = $goods_row->goods_name;
                $data[$index]['goods_price'] = $goods_row->goods_price;
            }
        });

        return array_values($data);
    }

    /**
     * 获取团购列表
     * 判断团购活动是否正常，判断团购商品是否正常
     * @param array $ids
     * @return Collection
     */
    public static function getNormalGroupbuy(array $ids = []) : Collection
    {
        return self::buildQuery()
            ->when($ids, function ($query) use ($ids) {
                return $query->whereIn('a.groupbuy_id', $ids);
            })
            ->get();
    }

    /**
     * 首页版块中获取补齐正在进行的团购活动
     * @param array $ids
     * @param int $size
     * @return Collection
     */
    public static function getOpenForumGroupbuy(array $ids, int $size) : Collection
    {
        return self::buildQuery()
            ->when($ids, function ($query) use ($ids) {
                return $query->whereNotIn('a.groupbuy_id', $ids);
            })
            ->limit($size)
            ->get();
    }

    private static function buildQuery()
    {
        $now = now()->toDateTimeString();
        return self::from('yf_groupbuy_base as a')
            ->select('a.*')
            ->leftJoin('yf_goods_base as b', 'b.goods_id', '=', 'a.goods_id')
            ->leftJoin('yf_goods_common as c', 'c.common_id', '=', 'b.common_id')
            ->where([
                ['a.groupbuy_endtime', '>', $now],
                ['a.groupbuy_starttime', '>', $now],
                ['a.groupbuy_state', '=', 2],
                ['b.goods_is_shelves', '=', 1],
                ['b.is_del', '=', 1],
                ['c.common_state', '=', 1],
                ['c.common_verify', '=', 1],
                ['c.is_del', '=', 1]
            ])
            ->latest('a.groupbuy_id');
    }

    /**
     * 商品团购详情
     * @param int $commonId
     * @return array
     */
    public static function getNormalGroupBuyDetailByCommonId(int $commonId) : array
    {
        $data = [];
        $detail = self::where([
                ['common_id', '=', $commonId],
                ['groupbuy_state', '=', self::NORMAL]
            ])
            ->with('goodsCommon')
            ->first();

        if ($detail && $detail->goodsCommon) {
            // 已结束
            if (now()->isAfter($detail->groupbuy_endtime)) {
                $detail->groupbuy_state = self::FINISHED;
                $detail->save();
            }
            // 未开始
            if (now()->isBefore($detail->groupbuy_starttime)) {
                $detail->groupbuy_state = self::WILLSTART;
            }

            $detail->reduce = $detail->goodsCommon->common_price - $detail->groupbuy_price;
            $detail->rate = sprintf("%.2f", $detail->groupbuy_price / $detail->goodsCommon->common_price * 10);
            $data = array_merge($detail->toArray(), $detail->goodsCommon->only('common_name', 'common_price'));
        }

        return $data;
    }
}
